package com.robot.admin.controller;

import com.alibaba.fastjson.JSON;
import com.robot.admin.client.GoodsClient;
import com.robot.admin.pojo.client.GoodsCategory;
import com.robot.admin.service.AdminService;
import entity.Result;
import entity.StatusCode;
import io.jsonwebtoken.Claims;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import util.CheckUtil;
import util.UpdateUtil;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * 商品分类模块
 *
 * @author wuyunbin
 */
@RestController
@CrossOrigin
@RequestMapping("/goodsCategory")
public class GoodsCategoryController {
    @Autowired
    private AdminService adminService;

    @Autowired
    private GoodsClient goodsClient;

    @Autowired
    private CheckUtil checkUtil;

    @Autowired
    private HttpServletRequest request;

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * 分页+多条件查询
     *
     * @param searchMap 查询条件封装
     * @param page      页码
     * @param size      页大小
     * @return 分页结果
     */
    @RequestMapping(value = "findGoodsCategoryBySearch/{page}/{size}", method = RequestMethod.POST)
    public Result findGoodsCategoryBySearch(@RequestBody Map searchMap, @PathVariable int page, @PathVariable int size) {
        Claims claims = (Claims) request.getAttribute("robot_admin");
        if (claims == null) {
            return new Result(StatusCode.ERROR_TOKEN_EXPIRED);
        }
        logger.info("claims.getId()=" + claims.getId());
        //前端调用findByToken接口检查过了,所以这里不再对管理员是否存在和状态进行判断

        return new Result(StatusCode.SUCCESS_QUERY, JSON.parseObject(goodsClient.thirdFindGoodsCategoryBySearch(searchMap, page, size)));
    }

    /**
     * 根据ID查询
     *
     * @param id ID
     * @return
     */
    @RequestMapping(value = "findGoodsCategoryById/{id}", method = RequestMethod.GET)
    public Result findGoodsCategoryById(@PathVariable String id) {
        Claims claims = (Claims) request.getAttribute("robot_admin");
        if (claims == null) {
            return new Result(StatusCode.ERROR_TOKEN_EXPIRED);
        }
        logger.info("claims.getId()=" + claims.getId());
        //前端调用findByToken接口检查过了,所以这里不再对管理员是否存在和状态进行判断

        return new Result(StatusCode.SUCCESS_QUERY, JSON.parseObject(goodsClient.thirdFindGoodsCategoryById(id)));
    }

    /**
     * 增加
     *
     * @param goodsCategory
     */
    @RequestMapping(value = "addGoodsCategory", method = RequestMethod.POST)
    public Result addGoodsCategory(@RequestBody GoodsCategory goodsCategory) {
        Claims claims = (Claims) request.getAttribute("robot_admin");
        if (claims == null) {
            return new Result(StatusCode.ERROR_TOKEN_EXPIRED);
        }
        logger.info("claims.getId()=" + claims.getId());
        //前端调用findByToken接口检查过了,所以这里不再对管理员是否存在和状态进行判断

        logger.info("goodsCategory=" + goodsCategory);
        if (goodsCategory.getName() == null || "".equals(goodsCategory.getName())) {
            return new Result(StatusCode.ERROR_GOODS_CATEGORY_NAME_REQUIRED);
        } else {
            if (JSON.parseObject(goodsClient.thirdFindGoodsCategoryByName(goodsCategory.getName()), GoodsCategory.class) != null) {
                return new Result(StatusCode.ERROR, "已存在该商品分类名称");
            }
        }
        if (goodsCategory.getParentId() != null && !"".equals(goodsCategory.getParentId()) && JSON.parseObject(goodsClient.thirdFindGoodsCategoryById(goodsCategory.getParentId()), GoodsCategory.class) == null) {
            return new Result(StatusCode.ERROR, "父级商品分类不存在");
        }
        if (goodsCategory.getSort() == null && "".equals(goodsCategory.getSort())) {
            goodsCategory.setSort("0");
        }
        goodsClient.thirdAddGoodsCategoryByGoodsCategory(JSON.toJSONString(goodsCategory));
        return new Result(StatusCode.SUCCESS_INSERTED);
    }

    /**
     * 修改
     *
     * @param goodsCategory
     */
    @RequestMapping(value = "updateGoodsCategory/{id}", method = RequestMethod.PUT)
    public Result updateGoodsCategory(@RequestBody GoodsCategory goodsCategory, @PathVariable String id) {
        Claims claims = (Claims) request.getAttribute("robot_admin");
        if (claims == null) {
            return new Result(StatusCode.ERROR_TOKEN_EXPIRED);
        }
        logger.info("claims.getId()=" + claims.getId());
        //前端调用findByToken接口检查过了,所以这里不再对管理员是否存在和状态进行判断

        logger.info("goodsCategory=" + goodsCategory);
        GoodsCategory goodsCategoryInDb = JSON.parseObject(goodsClient.thirdFindGoodsCategoryById(id), GoodsCategory.class);
        logger.info("goodsCategoryInDb=" + goodsCategoryInDb);
        if (goodsCategory == null) {
            return new Result(StatusCode.ERROR_GOODS_CATEGORY_DOES_NOTE_EXIST);
        }

        if (goodsCategory.getName() != null && !"".equals(goodsCategory.getName())) {
            //判断传入的分类名称是否不变
            if (!goodsCategory.getName().equals(goodsCategoryInDb.getName()) && JSON.parseObject(goodsClient.thirdFindGoodsCategoryByName(goodsCategory.getName()), GoodsCategory.class) != null) {
                return new Result(StatusCode.ERROR, "已存在该商品分类名称");
            }
        }
        if (goodsCategory.getParentId() != null && !"".equals(goodsCategory.getParentId()) && JSON.parseObject(goodsClient.thirdFindGoodsCategoryById(goodsCategory.getParentId()), GoodsCategory.class) == null) {
            return new Result(StatusCode.ERROR, "父级商品分类不存在");
        }
        if (goodsCategory.getSort() != null && !"".equals(goodsCategory.getSort())) {
            goodsCategoryInDb.setSort(goodsCategory.getSort());
        }
        goodsCategory.setId(id);
        UpdateUtil.copyNonNullProperties(goodsCategory, goodsCategoryInDb);
        goodsClient.thirdUpdateGoodsCategoryByGoodsCategory(JSON.toJSONString(goodsCategoryInDb));
        return new Result(StatusCode.SUCCESS_UPDATED);
    }

    /**
     * 删除
     *
     * @param id
     */
    @RequestMapping(value = "deleteGoodsCategory/{id}", method = RequestMethod.DELETE)
    public Result deleteGoodsCategory(@PathVariable String id) {
        Claims claims = (Claims) request.getAttribute("robot_admin");
        if (claims == null) {
            return new Result(StatusCode.ERROR_TOKEN_EXPIRED);
        }
        logger.info("claims.getId()=" + claims.getId());
        //前端调用findByToken接口检查过了,所以这里不再对管理员是否存在和状态进行判断

        Integer total = (Integer) JSON.parseObject(goodsClient.thirdFindGoodsByCategoryId(id, 1, 10)).get("total");
        logger.info("total=" + total);
        if (total != 0) {
            return new Result(StatusCode.ERROR_GOODS_CATEGORY_DOES_USED_DELETE);
        }
        goodsClient.thirdDeleteGoodsCategoryById(id);
        return new Result(StatusCode.SUCCESS_DELETED);
    }
}
